package res;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.lsp.io.logger.SysLogger;
import org.lsp.io.logger.SysLogger.Level;
import org.lsp.utils.CloneableImageIcon;
import org.lsp.view.GUI;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public abstract class SysRes {

	private static String strings;

	public final static CloneableImageIcon championLogo(
			final String championName) {
		return SysRes.image("champs/" + championName);
	}

	public final static CloneableImageIcon image(final String imageName) {
		return new CloneableImageIcon(new ImageIcon(
				GUI.class.getResource("/res/images/" + imageName + ".png")));
	}

	private static final void importStrings() {
		final StringBuffer sb = new StringBuffer();

		try (BufferedReader br = new BufferedReader(new InputStreamReader(
				SysRes.class.getResourceAsStream("/res/strings.xml"), "UTF-8"))) {
			for (int c = br.read(); c != -1; c = br.read()) {
				sb.append((char) c);
			}
		} catch (final UnsupportedEncodingException e1) {
			SysLogger.log(e1, "ERR8", Level.CRASH);
		} catch (final IOException e2) {
			SysLogger.log(e2, "ERR9", Level.CRASH);
		}

		SysRes.strings = sb.toString();
	}

	public final static String string(final int stringID) {
		if (SysRes.strings == null) {
			SysRes.importStrings();
		}
		DocumentBuilder docBuilder;
		Document doc = null;

		try {
			docBuilder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			doc = docBuilder.parse(new ByteArrayInputStream(SysRes.strings
					.getBytes("UTF-8")));
		} catch (SAXException | IOException | ParserConfigurationException ex) {
			SysLogger.log(ex, "ERR7", Level.CRASH);
		}

		final NodeList parent = doc.getElementsByTagName("STRING");
		return parent.item(stringID).getAttributes().getNamedItem("TEXT")
				.getNodeValue();
	}
}
